// src/components/CommonAside/index.js
/* eslint-disable */
import React, { useState } from 'react';
import { Menu, Layout, Button, Input ,message} from 'antd';
import * as Icon from "@ant-design/icons";
import { useNavigate, useLocation } from 'react-router-dom';
import MenuConfig from '../../config';
import { useDispatch } from "react-redux";
import { selectMenuList } from '../../store/reducers/tab';
import { searchArticles ,searchTests} from '../../api/EsIndex';
import './index.css'; // 引入样式文件
import logo from '../../assets/Logo.png'; // 引入本地图片
import { SearchOutlined, LogoutOutlined, DownOutlined } from '@ant-design/icons';

const { Header, Content } = Layout;

const iconToElement = (name) => React.createElement(Icon[name]);

const items = MenuConfig.map((icon) => {
  const child = {
    key: `${icon.path}`,
    icon: iconToElement(icon.icon),
    label: (
      <span>
        {icon.label}
        {icon.children && <DownOutlined style={{ fontSize: '12px', marginLeft: '4px' }} />}
      </span>
    )
  };
  if (icon.children) {
    child.children = icon.children.map(item => {
      return {
        key: item.path,
        label: item.label
      };
    });
  }
  return child;
});

const CommonAside = () => {
  const navigate = useNavigate();
  const location = useLocation(); // 使用 useLocation 钩子获取当前路径
  const dispatch = useDispatch();
  const [searchQuery, setSearchQuery] = useState(''); // State to hold the search query

  // 添加数据到store
  const setTabsList = (val) => {
    dispatch(selectMenuList(val));
  };

  // 点击菜单
  const selectMenu = (e) => {
    let data;
    MenuConfig.forEach((item) => {
      if (item.path === e.keyPath[e.keyPath.length - 1]) {
        data = item;
        if (e.keyPath.length > 1) {
          data = item.children.find((child) => child.path === e.key);
        }
      }
    });

    // 确保数据完整
    const menuItem = {
      path: data.path,
      name: data.name || data.path.replace('/', ''),  // 添加默认name
      label: data.label
    };

    console.log('Adding menu item:', menuItem);  // 添加日志
    setTabsList(menuItem);
    navigate(e.key);
  };

  // 退出登录
  const logout = () => {
    localStorage.removeItem('token');
    navigate('/login');
  };

  // Handle search input change
  const handleSearchChange = (e) => {
    setSearchQuery(e.target.value);
  };

  // Handle search button click
  // src/components/CommonAside/index.js
const handleSearch = async () => {
  try {
    const [articleResults, testResults] = await Promise.all([
      searchArticles(searchQuery),
      searchTests(searchQuery)
    ]);

    // 格式化文章结果
    const formattedArticles = articleResults.map(item => ({
      type: 'article',
      id: item.id,
      title: item.title,
      description: item.description,
      imageUrl: item.imageUrl,
      author: item.author,
      date: item.date,
      tags: item.tags || [],
      path: `/article/${item.id}` // 文章详情页路径
    }));

    // 格式化测试结果
    const formattedTests = testResults.map(item => ({
      type: 'test',
      id: item.id,
      title: item.topic,
      description: `类型: ${item.types}`,
      status: item.status,
      path: `/task/test` // 修改为正确的测试路径
    }));

    // 合并搜索结果
    const combinedResults = [...formattedArticles, ...formattedTests];

    // 导航到搜索结果页面
    navigate('/search-results', { 
      state: { 
        results: combinedResults,
        query: searchQuery 
      } 
    });
  } catch (error) {
    console.error('搜索失败:', error);
    message.error('搜索失败，请稍后重试');
  }
};

  return (
    <Layout className="layout-wrapper">
      <div className="fixed-header">
        {/* 头部区域 */}
        <div className="header-container">
          <div className="title-container">
            <img src={logo} alt="Logo" className="logo" />
            <h1 className="title-text">大学生心理健康平台</h1>
          </div>
          <div className="search-container">
            <Input
              placeholder='请输入想搜索的内容'
              value={searchQuery}
              onChange={handleSearchChange}
              style={{ height: '35px', marginRight: '15px' }}
            />
            <Button
              type='primary'
              htmlType='submit'
              onClick={handleSearch}
              style={{ height: '35px', marginRight: '15px' }}
            >
              <SearchOutlined />
            </Button>
          </div>
        </div>

        {/* 第二行标题 */}
        <div className="second-header">
          <Menu
            theme="light"
            mode="horizontal"
            selectedKeys={[location.pathname]}
            items={items}
            onClick={selectMenu}
            style={{ backgroundColor: '#fff', color: '#000', width: '100%' }}
          />
          <div className="logout-button-container">
            <Button
              type="primary"
              danger
              block
              onClick={logout}
              style={{ backgroundColor: '#e6f7ff', borderColor: '#fff', color: '#333', position: 'relative', left: '0', width: '80px', marginRight: '30px' }}
            >
              <LogoutOutlined />
            </Button>
          </div>
        </div>
      </div>
    </Layout>
  );
};

export default CommonAside;